<!-- eslint-disable vue/no-mutating-props -->
<script setup>
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElSwitch,
  ElUpload
} from 'element-plus'
import { onBeforeMount, onMounted, onUpdated, reactive, ref, onActivated, watch } from 'vue'

const emit = defineEmits(['remoteMethod', 'validatorRules'])
const props = defineProps({
  tableColumn: { type: Array },
  formData: { type: Object },
  // eslint-disable-next-line vue/require-prop-type-constructor
  isRead: false
})
const formDataCopy = reactive({ ...props.formData }) // 创建 formData 的副本
const formLabelWidth = ref(150)
const formRules = ref({})
const buildFormRules = () => {
  let _formRules = {}
  if (props.isRead) {
    formRules.value = _formRules
    return false
  }
  for (const column of props.tableColumn.filter((item) => item.isForm)) {
    const rules = []
    if (column.required) {
      rules.push({
        required: column.required,
        message: `请输入${column.label}`,
        trigger: 'blur'
      })
    }
    if (column.formType === 'input' && column.max > 0) {
      rules.push({
        min: column.min || 0,
        max: column.max || 0,
        message: `${column.label}长度不能大于${column.max}`,
        trigger: 'blur'
      })
    }
    if (column.validatorRules) {
      rules.push({
        validator: (rule, value, callback) =>
          emit('validatorRules', column.prop, rule, value, callback)
      })
    }
    _formRules[column.prop] = rules
  }
  formRules.value = _formRules
}

const buildFormSelData = async () => {
  for (const key in props.formData) {
    formDataCopy[key] === 0 ? delete props.formData[key] : null
  }
}

let isThrottling = ref(false)
const timer = ref(null)
const remoteMethod = async (query, f) => {
  if (query === '') {
    return
  }
  // 如果已经在节流控制中，则直接返回，不执行后续操作
  if (isThrottling.value) return

  // 设置节流控制标志，防止在等待期间再次触发
  isThrottling.value = true

  await emit('remoteMethod', query, f)

  // 设置节流时间，之后重置标志允许再次执行
  clearTimeout(timer.value) // 确保只有最后一次设置的定时器被执行
  timer.value = setTimeout(() => {
    isThrottling.value = false
  }, 500) // 设置和防抖相同的时间间隔，或根据需要调
}

const ruleFormRef = ref()
const resetFields = () => {
  console.log(ruleFormRef.value)
  ruleFormRef.value.resetFields()
}
onBeforeMount(() => {
  buildFormRules()
})
onMounted(async () => {
  await buildFormSelData()
  ruleFormRef.value.clearValidate()
})

watch(
  () => props.isRead,
  (newValue, oldValue) => {
    // 这里处理isRead变化后的逻辑
    console.log(`isRead变化了，新值为：${newValue}, 旧值为：${oldValue}`)
    buildFormRules()
  }
)

defineExpose({
  resetFields,
  buildFormSelData,
  ruleFormRef
})
</script>

<template>
  <el-form :model="formData" :rules="formRules" ref="ruleFormRef">
    <el-form-item
      v-for="(f, fk) in tableColumn.filter((item) => item.isForm)"
      :key="fk"
      :label="f.label + ':'"
      :label-width="formLabelWidth"
      :prop="f.prop"
    >
      <div class="form-item">
        <div>
          <div v-if="isRead">
            <span v-if="f.formType === 'radio'">{{ f.enum[formData[f.prop]] }}</span>
            <span v-else-if="f.formType === 'select'">
              {{
                f.asyncSelData.find((i) => i.id === formData[f.prop])?.name ||
                f.asyncSelData.find((i) => i.id === formData[f.prop])?.value
              }}
            </span>
            <span v-else>{{ formData[f.prop] }}</span>
          </div>
          <!-- children start -->
          <div class="childrenForm" v-else-if="!isRead && f.formType === 'custom'">
            <el-form-item v-for="(c, ck) in f.children" :key="ck" :prop="c.prop">
              <el-input
                v-if="c.formType === 'input'"
                v-model="formDataCopy[c.prop]"
                :placeholder="`请输入${c.label}`"
                :type="c.inputType"
                autocomplete="off"
                :maxlength="c.max || -1"
                :minlength="c.min || 0"
                show-word-limit
              />
              <el-input-number
                v-else-if="c.formType === 'number'"
                v-model="formDataCopy[c.prop]"
                :placeholder="`请输入${c.label}`"
                controls-position="right"
                :min="c.min"
                :max="c.max"
              />
              <el-select
                v-else-if="c.formType === 'select'"
                v-model="formDataCopy[c.prop]"
                filterable
                :multiple="c.multiple || false"
                :clearable="true"
                :placeholder="`请选择${c.label}`"
              >
                <el-option
                  v-for="(sel, selKey) in c.asyncSelData"
                  :key="selKey"
                  :value="sel.id"
                  :label="sel.name || sel.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <!-- children end -->

          <el-input
            v-else-if="!isRead && f.formType === 'input'"
            v-model="formDataCopy[f.prop]"
            :placeholder="`请输入${f.label}`"
            :type="f.inputType"
            autocomplete="off"
            :maxlength="f.max || -1"
            :minlength="f.min || 0"
            show-word-limit
          />
          <el-input-number
            v-else-if="!isRead && f.formType === 'number'"
            v-model="formDataCopy[f.prop]"
            :placeholder="`请输入${f.label}`"
            controls-position="right"
            :min="f.min"
            :max="f.max"
          />
          <el-input
            v-else-if="!isRead && f.formType === 'textarea'"
            v-model="formDataCopy[f.prop]"
            :placeholder="`请输入${f.label}`"
            type="textarea"
            autocomplete="off"
            :maxlength="f.max || -1"
            :minlength="f.min || 0"
            show-word-limit
          />
          <el-radio-group
            v-else-if="!isRead && f.formType === 'radio'"
            v-model="formDataCopy[f.prop]"
          >
            <el-radio
              v-for="(sel, selKey) in Object.keys(f.enum).filter((i) => i > 0)"
              :key="selKey"
              :value="Number(sel)"
              >{{ f.enum[sel] }}</el-radio
            >
          </el-radio-group>

          <el-select
            v-else-if="!isRead && f.formType === 'select'"
            v-model="formDataCopy[f.prop]"
            filterable
            :multiple="f.multiple"
            :clearable="true"
            :placeholder="`请选择${f.label}`"
          >
            <el-option
              v-for="(sel, selKey) in f.asyncSelData"
              :key="selKey"
              :value="sel.id"
              :label="sel.name || sel.value"
            />
          </el-select>

          <el-select
            v-else-if="!isRead && f.formType === 'select_remote'"
            v-model="formDataCopy[f.prop]"
            filterable
            remote
            :remote-method="(query) => remoteMethod(query, f)"
            :multiple="f.multiple"
            :placeholder="`请选择${f.label}`"
          >
            <el-option
              v-for="(sel, selKey) in f.asyncSelData"
              :key="selKey"
              :value="sel.id"
              :label="sel.name || sel.value"
            />
          </el-select>

          <el-switch
            v-else-if="!isRead && f.formType === 'switch'"
            v-model="formDataCopy[f.prop]"
          />

          <el-upload
            v-else-if="!isRead && f.formType === 'image'"
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData[f.prop]" :src="formData[f.prop]" alt="" class="avatar" />
            <div class="upLoadImg">
              <img class="addImg" src="/src/assets/addIm g.png" alt="" />
              <div class="title">上传图片</div>
            </div>
          </el-upload>
        </div>
        <div class="tips">{{ f.tips }}</div>
      </div>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="less">
.form-item {
  display: flex;
  width: 100%;
  > div:first-of-type {
    width: 100%;
  }
  .tips {
    flex: none;
    padding-left: 10px;
    color: rgb(192, 196, 204);
  }
}
::v-deep .el-input__inner::-webkit-input-placeholder {
  color: #b6bcc4;
  font-size: 12px;
}

::v-deep .el-textarea__inner::-webkit-input-placeholder {
  color: #b6bcc4;
  font-size: 12px;
}

::v-deep(.el-form-item__label) {
  font-weight: 500;
  color: #515a6e;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

//上传的样式
.upLoadImg {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 10px 15px;
  text-align: center;
  width: 120px;

  .title {
    font-size: 12px;
    color: #8c939d;
  }

  .addImg {
    width: 40px;
    height: 40px;
  }
}

.childrenForm {
  display: flex;
  width: 100%;
  .el-input-number {
    width: 100%;
  }
  .el-form-item {
    width: 100%;
    margin-right: 10px;
    &:last-of-type {
      margin-right: 0;
    }
  }
  .el-select {
    width: 100%;
  }
}
</style>
